#include "PacmanEntity.h"
#include "Application.h"
#include <iostream>

#define AnimationIndex_Max 3
#define AnimationTickInterval 2


PacmanEntity::PacmanEntity(void)
{
	Initialize();
}

PacmanEntity::PacmanEntity(int pX, int pY)
{
	_X = pX;
	_Y = pY;
	Initialize();
}

PacmanEntity::~PacmanEntity(void){}

void PacmanEntity::Think()
{
	_IndexAnimation.Tick();
	Application::Instance().Level().RefreshRequest(*this);
	CheckInput();
	Move();
}

void PacmanEntity::Move()
{
	//Take desized orientation into account
	if(_DesiredOrientation != _Orientation 
		&& Application::Instance().Level().CanTakeOrientation(_DesiredOrientation, *this))
		_Orientation = _DesiredOrientation;

	//Check the current orientation
	if(!Application::Instance().Level().CanContinueThisWay(_Orientation, *this))
	{
		_Orientation = None;
		_DesiredOrientation = None;
	}

	//Move according to orientation
	switch(_Orientation)
	{
		case Right:
			_X++;
			break;
		case Down:
			_Y++;
			break;
		case Left:
			_X--;
			break;
		case Up:
			_Y--;
			break;
	}
}

void PacmanEntity::CheckInput()
{
	if(Application::Instance().InputManager().RightInput())
		_DesiredOrientation = Right;
	else if(Application::Instance().InputManager().DownInput())
		_DesiredOrientation = Down;
	else if(Application::Instance().InputManager().LeftInput())
		_DesiredOrientation = Left;
	else if(Application::Instance().InputManager().UpInput())
		_DesiredOrientation = Up;
}

void PacmanEntity::Draw(sf::RenderWindow &pRenderWindow)
{
	_Sprite.SetPosition(_X + (Conf_LevelElementSize/2.f), _Y + (Conf_LevelElementSize/2.f));
	_Sprite.SetSubRect(sf::IntRect(_IndexAnimation.Index()*Conf_LevelElementSize,0,(_IndexAnimation.Index()+1)*Conf_LevelElementSize,Conf_LevelElementSize));
	_Sprite.SetCenter(Conf_LevelElementSize/2,Conf_LevelElementSize/2);
	switch(_Orientation)
	{
		case Right: _Sprite.SetRotation(0); break;
		case Down: _Sprite.SetRotation(-90); break;
		case Left: _Sprite.SetRotation(180); break;
		case Up: _Sprite.SetRotation(90); break;
	}
	pRenderWindow.Draw(_Sprite);
}

void PacmanEntity::Initialize()
{
	_Sprite.SetImage(Application::Instance().ImageManager().GetImage(Pacman));
	_Sprite.SetBlendMode(sf::Blend::Alpha);
	_IndexAnimation.Create(0, AnimationIndex_Max, RepeatFlip, AnimationTickInterval);
	_Orientation = None;
	_DesiredOrientation = None;
}






